import 'dart:io';

import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/app_string.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_plugin_record/flutter_plugin_record.dart';
import 'package:path_provider/path_provider.dart';

/**
 * 2021.7.9
 * 录音页面
 * alex
 */

class VoicePage extends StatefulWidget {
  const VoicePage({Key key}) : super(key: key);

  @override
  _VoicePageState createState() => _VoicePageState();
}

class _VoicePageState extends State<VoicePage> {
  BuildContext _context;
  FlutterPluginRecord recordPlugin = new FlutterPluginRecord();

  String filePath = "";
  bool isPlaying = false;
  bool isF = true;

  @override
  void initState() {
    super.initState();
    _initRecordMp3();

    ///初始化方法的监听
    recordPlugin.responseFromInit.listen((data) {
      if (data) {
        print("初始化成功");
      } else {
        print("初始化失败");
      }
    });

    /// 开始录制或结束录制的监听
    recordPlugin.response.listen((data) {
      if (data.msg == "onStop") {
        ///结束录制时会返回录制文件的地址方便上传服务器
        print("onStop  文件路径" + data.path);
        filePath = data.path;
        print("onStop  时长 " + data.audioTimeLength.toString());
      } else if (data.msg == "onStart") {
        print("onStart --");
      } else {
        print("--" + data.msg);
      }
    });

    ///录制过程监听录制的声音的大小 方便做语音动画显示图片的样式
    recordPlugin.responseFromAmplitude.listen((data) {
      var voiceData = double.parse(data.msg);
      print("振幅大小   " + voiceData.toString());
    });

    recordPlugin.responsePlayStateController.listen((data) {
      print("播放路径   " + data.playPath);
      print("播放状态   " + data.playState);
    });
  }

  @override
  Widget build(BuildContext context) {
    _context = context;

    return Scaffold(
      appBar: _appBar(),
      body: Container(
        padding: EdgeInsets.fromLTRB(width(50), height(80), width(50), 0),
        width: MediaQuery.of(context).size.width,
        color: Colors.white,
        child: Column(
          children: [
            Text(
              AppString.voiceHint,
              style: TextStyle(color: AppColor.colorDefaultText, fontSize: 14),
            ),
            _voiceTimeHint(),
            _voiceButton(),
          ],
        ),
      ),
    );
  }

  _appBar() {
    return AppBar(
      automaticallyImplyLeading: false,
      actions: <Widget>[
        Container(
          margin: EdgeInsets.fromLTRB(0, 10, 15, 10),
          width: width(64),
          height: height(10),
          child: ElevatedButton(
            style: ButtonStyle(
              padding: MaterialStateProperty.all(EdgeInsets.zero),
              backgroundColor: MaterialStateProperty.all(AppColor.colorTheme),
            ),
            onPressed: () {},
            child: Text(
              "确认",
              style: TextStyle(color: Colors.white, fontSize: 14),
            ),
          ),
        )
      ],
      title: InkWell(
        onTap: () {
          Navigator.of(context).pop();
        },
        child: Text(
          '取消',
          style: TextStyle(color: AppColor.colorDefaultText, fontSize: 16),
        ),
      ),
      elevation: 0,
      backgroundColor: Colors.white,
    );
  }

  /**
   * 录制时长
   */
  String _time = "00:00";

  _voiceTimeHint() {
    return Container(
      child: Text(
        "--------$_time--------",
        style: TextStyle(fontSize: 12, color: AppColor.colorHintText),
      ),
    );
  }

  /**
   * 播放按钮
   */
  _voiceButton() {
    return IconButton(
        onPressed: () {
          setState(() {
            isPlaying = !isPlaying;
            if (isPlaying) {
              if (isF) {
                start();
              }
            }
          });
        },
        icon: Icon(
          isPlaying ? Icons.pause : Icons.play_arrow,
          color: Colors.red[200],
        ));
  }

  void _requestAppDocumentsDirectory() {
//    if(Platform.isIOS){
//      //ios相关代码
//      setState(() {
//        getApplicationDocumentsDirectory().then((value) {
//          String nowDataTimeStr = DateUtil.getNowDateMs().toString();
//          String wavPath = value.path + "/" + nowDataTimeStr + ".wav";
//          startByWavPath(wavPath);
//        });
//      });
//    }else if(Platform.isAndroid){
//      //android相关代码
//    }

    setState(() {
      getApplicationDocumentsDirectory().then((value) {
        String nowDataTimeStr = DateUtil.getNowDateMs().toString();
        // TODO  注意IOS 传递的Mp3路径一定是以 .MP3 结尾
        String wavPath = "";
        if (Platform.isIOS) {
          wavPath = value.path + "/" + nowDataTimeStr + ".MP3";
        } else {
          wavPath = value.path + "/" + nowDataTimeStr;
        }
        startByWavPath(wavPath);
      });
    });
  }

  ///初始化语音录制的方法
  void _initRecordMp3() async {
    recordPlugin.initRecordMp3();
  }

  ///开始语音录制的方法
  void start() async {
    recordPlugin.start();
  }

  ///根据传递的路径进行语音录制
  void startByWavPath(String wavPath) async {
    recordPlugin.startByWavPath(wavPath);
  }

  ///停止语音录制的方法
  void stop() {
    recordPlugin.stop();
  }

  ///播放语音的方法
  void play() {
    recordPlugin.play();
  }

  ///播放指定路径录音文件  url为iOS播放网络语音，file为播放本地语音文件
  void playByPath(String path, String type) {
    recordPlugin.playByPath(path, type);
  }

  ///暂停|继续播放
  void pause() {
    recordPlugin.pausePlay();
  }

  @override
  void dispose() {
    /// 当界面退出的时候是释放录音资源
    recordPlugin.dispose();
    super.dispose();
  }

  void stopPlay() {
    recordPlugin.stopPlay();
  }
}
